<template>
  <div class="order">
    <div
      @click="goAddressList()"
      v-if="checkedAddress.tel == undefined"
      style="
        width: 100%;
        background: white;
        height: 130px;
        text-align: center;
        margin-top: 10px;
        padding-top: 20px;
      "
    >
      <img :src="aress" alt="" width="50px" height="50px" />
      <p style="color: #8a8a8a">请选择收货地址</p>
    </div>

    <van-cell-group v-if="checkedAddress.tel != undefined">
      <van-cell isLink @click="goAddressList()" title="收货地址">
        <div slot="label">
          <div>
            <span>{{ checkedAddress.name }} </span>
            <span>{{ checkedAddress.tel }} </span>
          </div>
          <div>
            {{ checkedAddress.addressDetail }}
          </div>
        </div>
      </van-cell>
    </van-cell-group>

    <!-- <van-cell-group>
      <van-cell
        class="order-coupon"
        title="优惠券"
        is-link
        :value="getCouponValue()"
        @click="getCoupons"
      />
    </van-cell-group> -->

    <!-- 优惠券列表 -->
    <van-popup v-model="showList" position="bottom">
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
        @exchange="onExchange"
      />
    </van-popup>

    <van-card
      v-for="item in checkedGoodsList"
      :key="item.id"
      :title="item.goodsName"
      :num="item.number"
      :price="item.price + '.00'"
      :thumb="item.picUrl"
    >
      <div slot="desc">
        <div class="van-card__desc">
          <van-tag
            plain
            style="margin-right: 6px"
            v-for="(spec, index) in item.specifications"
            :key="index"
          >
            {{ item.payType == 0 ? spec : getSpec() }}
          </van-tag>
        </div>
      </div>

      <div
        v-if="item.giftList !== undefined && item.giftList.length > 0"
        slot="footer"
        style="display: flex; width: calc(100vw - 130px); margin-top: 5px"
      >
        <span style="font-weight: bold; color: #000; float: left">赠品</span>
        <div
          style="
            margin-left: 6px;
            display: flex;
            flex-direction: column;
            font-size: 11px;
            width: calc(100% - 30px);
          "
        >
          <div
            v-for="(gift, index) in item.giftList"
            :key="index"
            style="width: 100%; line-height: 16px"
          >
            <span
              style="
                width: calc(100% - 18px);
                float: left;
                display: inline-block;
                text-align: left;
                display: inline-block;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ gift.giftName }}</span
            ><span style="float: right; margin-left: 5px"
              >*{{ gift.num * item.number }}</span
            >
          </div>
        </div>
      </div>
    </van-card>

    <van-cell-group>
      <van-cell title="商品金额">
        <span class="red">{{ (goodsTotalPrice * 100) | yuan }}</span>
      </van-cell>
      <van-cell title="预付金额" v-if="payType != 0">
        <span class="red">{{ (prePrice * 100) | yuan }}</span>
      </van-cell>
      <van-cell title="邮费">
        <!-- <span class="red">{{ freightPrice * 100| yuan}}</span> -->
        <span class="red">到付</span>
      </van-cell>
      <van-cell title="优惠券">
        <span class="red">-{{ (couponPrice * 100) | yuan }}</span>
      </van-cell>
      <van-field v-model="message" placeholder="请输入备注" label="订单备注">
        <template slot="icon">{{ message.length }}/50</template>
      </van-field>
    </van-cell-group>

    <van-submit-bar
      :price="payType == 0 ? actualPrice * 100 : prePrice * 100"
      label="总计："
      buttonText="提交订单"
      :disabled="isDisabled"
      @submit="onSubmit"
    />
  </div>
</template>

<script>
import { Card, Tag, ard, Field, SubmitBar, Toast } from 'vant';
import { CouponCell, CouponList, Popup } from 'vant';
import {
  cartCheckout,
  orderSubmit,
  couponSelectList,
  authInfo,
} from '@/api/api';
import aress from '@/assets/images/aress.png';
import {
  getLocalStorage,
  setLocalStorage,
  removeLocalStorage,
} from '@/utils/local-storage';
import dayjs from 'dayjs';

export default {
  data() {
    return {
      checkedGoodsList: [],
      aress: aress,
      checkedAddress: {},
      availableCouponLength: 0, // 可用的优惠券数量
      goodsTotalPrice: 0, //商品总价
      prePrice: 0, // 预付金额
      payType: 0, // 支付类型
      freightPrice: 0, //快递费
      couponPrice: 0, //优惠券的价格
      grouponPrice: 0, //团购优惠价格
      orderTotalPrice: 0, //订单总价
      actualPrice: 0, //实际需要支付的总价
      message: '',
      isDisabled: false,
      showList: false,
      chosenCoupon: -1,
      coupons: [],
      disabledCoupons: [],
    };
  },
  watch: {},
  created() {
    this.init();
  },

  methods: {
    getSpec() {
      if (this.payType == 1) {
        return '试机';
      } else if (this.payType == 2) {
        return '定金';
      } else if (this.payType == 3) {
        return '全款';
      }
    },
    onSubmit() {
      const { AddressId, CartId, CouponId } = getLocalStorage(
        'AddressId',
        'CartId',
        'CouponId'
      );
      //removeLocalStorage('AddressId');
      if (AddressId === null || AddressId == '0') {
        //console.log(JSON.stringify(AddressId));
        Toast.fail('请设置收货地址');
        return;
      }

      this.isDisabled = true;
      authInfo().then((res) => {
        this.userId = res.data.data.userId;
        this.mobile = res.data.data.mobile || '';
        let status = res.data.data.status;
        if (status == 0) {
          //未认证
          Toast('请先验证手机号!');
          this.$router.push(`/check`);
          return;
        } else {
          Toast.loading({
            message: '加载中...',
          });
          orderSubmit({
            addressId: AddressId,
            cartId: CartId,
            couponId: CouponId,
            grouponLinkId: 0,
            grouponRulesId: 0,
            message: this.message,
          })
            .then((res) => {
              // 下单成功，重置下单参数。
              setLocalStorage({ AddressId: 0, CartId: 0, CouponId: 0 });

              let orderId = res.data.data;
              this.$router.push({
                name: 'payment',
                query: { orderId: orderId, payType: this.payType },
              });
            })
            .catch((error) => {
              this.isDisabled = false;
              //this.$toast(error.data.errmsg);
            });
        }
      });
    },
    goAddressList() {
      this.$router.push({
        path: '/user/address',
      });
    },
    // getCouponValue() {
    //   if (this.couponPrice !== 0) {
    //     return '-¥' + this.couponPrice + '.00元';
    //   }
    //   if (this.availableCouponLength !== 0) {
    //     return this.availableCouponLength + '张可用';
    //   }
    //   return '没有可用优惠券';
    // },
    getCoupons() {
      const { AddressId, CartId, CouponId } = getLocalStorage(
        'AddressId',
        'CartId',
        'CouponId'
      );
      couponSelectList({ cartId: CartId, grouponRulesId: 0 }).then((res) => {
        var cList = res.data.data;
        this.coupons = [];
        for (var i = 0; i < cList.length; i++) {
          var c = cList[i];
          var coupon = {
            id: c.id,
            name: c.name,
            condition: c.min,
            value: c.discount * 100,
            description: c.desc,
            startAt: new Date(c.startTime).getTime() / 1000,
            endAt: new Date(c.endTime).getTime() / 1000,
            valueDesc: c.discount,
            unitDesc: '元',
          };
          this.coupons.push(coupon);

          if (c.id === this.couponId) {
            this.chosenCoupon = i;
            break;
          }
        }

        this.showList = true;
      });
    },
    async init() {
      const { AddressId, CartId, CouponId } = await getLocalStorage(
        'AddressId',
        'CartId',
        'CouponId'
      );

      cartCheckout({
        cartId: CartId,
        addressId: AddressId,
        couponId: CouponId,
        grouponRulesId: 0,
      }).then((res) => {
        var data = res.data.data;
        this.checkedGoodsList = data.checkedGoodsList;
        this.checkedAddress = data.checkedAddress;
        this.availableCouponLength = data.availableCouponLength;
        this.actualPrice = data.actualPrice;
        this.couponPrice = data.couponPrice;
        this.grouponPrice = data.grouponPrice;
        this.freightPrice = data.freightPrice;
        this.goodsTotalPrice = data.goodsTotalPrice;
        this.prePrice = data.prePrice;
        this.payType = data.payType;
        this.orderTotalPrice = data.orderTotalPrice;

        setLocalStorage({
          AddressId: data.addressId,
          CartId: data.cartId,
          CouponId: data.couponId,
        });
      });
    },
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index;

      if (index === -1) {
        setLocalStorage({ CouponId: -1 });
      } else {
        const couponId = this.coupons[index].id;
        setLocalStorage({ CouponId: couponId });
      }

      this.init();
    },
    onExchange() {
      this.$toast('兑换暂不支持');
    },
  },

  components: {
    [Toast.name]: Toast,
    [SubmitBar.name]: SubmitBar,
    [Card.name]: Card,
    [Field.name]: Field,
    [Tag.name]: Tag,
    [CouponCell.name]: CouponCell,
    [CouponList.name]: CouponList,
    [Popup.name]: Popup,
  },
};
</script>


<style lang="scss" scoped>
.order-coupon {
  margin-top: 10px;
}

.van-card__footer {
  padding-left: 98px;
}
</style>